/**
 * Copyright 2011-2012. Chongqing CRun Information Industry Co.,Ltd.
 * All rights reserved. <a>http://www.crunii.com</a>
 */
package ysyh55.android.base.util;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Administrator
 * @date 2012-11-22
 */
public class CommonUtils {
	private static long lastClickTime;

	/**
	 * 防止控件被重复点击
	 * 
	 * @return Examples:</br> public void onClick(View v) {</br> if
	 *         (Utils.isFastDoubleClick()) {</br> return;</br> }else{</br>
	 *         //弹出Toast或者Dialog</br> }</br> }</br>
	 */
	public static boolean isFastDoubleClick() {
		long time = System.currentTimeMillis();
		long timeD = time - lastClickTime;
		if (0 < timeD && timeD < 800) {
			return true;
		}
		lastClickTime = time;
		return false;
	}

	/**
	 * 时间格式化
	 * 
	 * @param date
	 * @param pattern
	 *          如："yyyy年MM月dd日 HH时mm分ss秒","yyyy-MM-dd HH:mm:ss"
	 * @return
	 */
	public static String timeFormat(Date date, String pattern) {
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);

		return sdf.format(date);

	}

	/**
	 * 清楚字符串中的HTml代码,保留换行 段落变成换行
	 * 
	 * @param input
	 * @param length
	 * @return
	 */
	public static String splitAndFilterString(String input, int length) {
		if (input == null || input.trim().equals("")) {
			return "";
		}
		// <p>段落替换为换行
		input = input.replaceAll("<p .*?>", "\r\n");
		// <br><br/>替换为换行
		input = input.replaceAll("<br\\s*/?>", "\r\n");
		input = input.replaceAll("(\r?\n(\\s*\r?\n)+)", "\r\n");
		// 去掉所有html元素,
		String str = input.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll("<[^>]*>", "");
		str = str.replaceAll("[(/>)<]", "");
		int len = str.length();
		if (len <= length) {
			return str;
		} else {
			str = str.substring(0, length);
			str += "......";
		}
		return str;
	}

	/**
	 * 得到网页中图片的地址
	 */
	public static List<String> getImgStr(String htmlStr) {
		String img = "";
		Pattern p_image;
		Matcher m_image;
		List<String> pics = new ArrayList<String>();

		String regEx_img = "<img.*src=(.*?)[^>]*?>"; // 图片链接地址
		p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
		m_image = p_image.matcher(htmlStr);
		while (m_image.find()) {
			img = img + "," + m_image.group();
			Matcher m = Pattern.compile("src=\"?(.*?)(\"|>|\\s+)").matcher(img); // 匹配src
			while (m.find()) {
				pics.add(m.group(1));
			}
		}
		return pics;
	}

	/**
	 * 得到网页中图片的地址
	 */
	public static String getSwfStr(String htmlStr) {
		String img = "";
		Pattern p_image;
		Matcher m_image;
		String regEx_img = "[a-zA-z]+://[^\\s]*(.swf|.flv)";// swf地址
		p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
		m_image = p_image.matcher(htmlStr);
		while (m_image.find()) {
			img = m_image.group();
		}
		return img;
	}
}
